package com.qqn.zcy.temp03;

import java.util.Stack;

/**
 * 用栈结构实现队列结构 *****
 *
 */
public class Code06_TwoStacksImplementQueue {

	public static class TwoStacksQueue {
		public Stack<Integer> stackPush;
		public Stack<Integer> stackPop;

		public TwoStacksQueue() {
			stackPush = new Stack<Integer>();
			stackPop = new Stack<Integer>(); // pop 栈拿完才能继续从 push 栈中 往 pop 栈中拿数据
		}

		// push栈向pop栈倒入数据
		private void pushToPop() {
			if (stackPop.empty()) {
				while (!stackPush.empty()) { // 倒到push被搬空为止
					stackPop.push(stackPush.pop());
				}
			}
		}

		/**
		 * 用户要往队列中增加数的方法  先往 push栈中放
		 * @param pushInt
		 */
		public void add(int pushInt) {
			stackPush.push(pushInt);
			pushToPop(); // 检查能不能倒入 pop 栈
		}

		/**
		 * 用户要从队列中拿数据
		 * @return
		 */
		public int poll() {
			if (stackPop.empty() && stackPush.empty()) {
				throw new RuntimeException("Queue is empty!");
			}
			pushToPop();
			return stackPop.pop();
		}

		/**
		 * peek 只是取值但是不弹出
		 * @return
		 */
		public int peek() {
			if (stackPop.empty() && stackPush.empty()) {
				throw new RuntimeException("Queue is empty!");
			}
			pushToPop();
			return stackPop.peek();
		}
	}

	public static void main(String[] args) {
		TwoStacksQueue test = new TwoStacksQueue();
		test.add(1);
		test.add(2);
		test.add(3);
		System.out.println(test.peek());
		System.out.println(test.poll());
		System.out.println(test.peek());
		System.out.println(test.poll());
		System.out.println(test.peek());
		System.out.println(test.poll());
	}

}
